from flask import render_template, request, jsonify, session, make_response, redirect, url_for

from models import db
from models.index import User
from . import passport_blu


@passport_blu.route("/signin.html", methods=["GET", "POST"])
def signin():
    if request.method == 'GET':
        return render_template("signin.html")

    telephone = request.json.get("telephone")
    password = request.json.get("password")
    user = db.session.query(User).filter(User.telephone == telephone, User.password == password).first()
    if not user:
        return jsonify({
            "errno": 1002,
            "errmsg": "用户名或密码错误"
        })
    session["user_id"] = user.id
    return jsonify({
        "errno": 0,
        "errmsg": "登录成功"
    })


@passport_blu.route("/signup.html", methods=["POST", "GET"])
def signup():
    if request.method == 'GET':
        return render_template("signup.html")
    user_name = request.json.get("user_name")
    image_code = request.json.get("image_code")
    telephone = request.json.get("telephone")
    password = request.json.get("password")
    print(user_name, image_code, telephone, password)
    if not image_code.upper() == session.get("img"):
        ret = {
            "errno": 1001,
            "errmsg": "验证码错误"
        }
        return jsonify(ret)
    if db.session.query(User).filter(User.telephone == telephone).first():
        ret = {
            "errno": 1004,
            "errmsg": "该手机号已经注册"
        }
        return jsonify(ret)
    user = User()
    user.name = user_name
    user.telephone = telephone
    user.password = password
    try:
        db.session.add(user)
        db.session.commit()
        session['user_id'] = user.id
        ret = {
            "errno": 0,
            "errmsg": "注册成功"
        }
    except:
        ret = {
            "errno": 1002,
            "errmsg": "注册失败"
        }
    return jsonify(ret)


@passport_blu.route('/image_code')
def image_code():
    from utils.captcha.captcha import captcha

    # 生成验证码
    # hash值  验证码值  图片内容
    name, text, image = captcha.generate_captcha()

    # print("刚刚生成的验证码：", text)
    session['img'] = text.upper()
    # 返回响应内容
    resp = make_response(image)
    return resp


@passport_blu.route("/logout.html")
def logout():
    session.clear()
    return redirect(url_for("passport.signin"))
